import { BrowserRouter, HashRouter, Switch, Route, Redirect } from "react-router-dom"
import { Suspense } from "react"

export const RouterView = ({routes}) => {
    return (
        <Suspense fallback={<div>loading...</div>}>
            <Switch>
                {
                   routes.filter(({redirect})=>!redirect).map(item => (
                       <Route path={item.path} key={item.name} render={
                           (props) => {
                               const PageCom = item.component;
                               document.title = item.meta?.title
                               return <PageCom {...props}/>
                           }
                       } />
                   )).concat(routes.filter(({redirect})=>redirect).map(item => (
                       <Redirect to={item.redirect} from={item.path} key={item.path} />
                   )))
                }
            </Switch>
        </Suspense>
    )
}


const Router = ({routes,mode='history'}) => {
    return (
        mode === 'history' ? (
            <BrowserRouter>
                <RouterView routes={routes} />
            </BrowserRouter>
        ) : (
            <HashRouter>
                <RouterView routes={routes} />
            </HashRouter>
        ) 
    )
}


export default Router;